package cn.tsmchina.one.dao.category;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.tsmchina.one.dao.BaseDaoSupport;
import cn.tsmchina.one.domain.category.Category;
import cn.tsmchina.one.domain.user.Customer;
import cn.tsmchina.one.util.C;

@Repository
public class CategoryDaoImpl extends BaseDaoSupport<Category> implements CategoryDao
{

	@Autowired 
	private SessionFactory sessionFactory;
	@Override
	public List<Category> getOneLevelCategories(long customerId) {
		String hql = "from Category c where length(c.cid)=4 and customerId=?";
		return lists(hql, customerId);
	}

	@Override
	public List<Category> getChildrenByParent(String parentCid, long customerId) {
		int pidLength = parentCid.length();
		int childrenIdLength = pidLength + 5;
		String hql = "from Category c where customerId=? and length(c.cid)= ? and c.cid like ?";
		return lists(hql, new Object[]{customerId, childrenIdLength, parentCid+"%"});
	}

	@Override
	public Category getById(int id) {
		return super.findById(id);
	}

	@Override
	public List<Category> getOneLevelCategories(int page, long customerId) {
		String hql = "from Category c where length(c.cid)=4 and customerId=?";
		return lists(hql, page, C.Paging.SIZE, new Object[]{customerId});
	}

	@Override
	public void updateCategory(Category category) {
		update(category);
	}

	@Override
	public void deleteCategory(int id) {
		delete(id);
	}

	@Override
	public void addCategory(Category category) {
		add(category);
	}

	@Override
	public Category getByCategoryCid(String categoryCid, long customerId) {
		String hql = "from Category c where c.cid=? and customerId=?";
		return lists(hql, new Object[]{categoryCid, customerId}).get(0);
	}

	@Override
	public Category getByCategoryLoginId(Integer loginId) {
		// TODO Auto-generated method stub
		if(null != loginId){
			@SuppressWarnings("unchecked")
			List<Category> list = sessionFactory.getCurrentSession().
				createQuery("from Category where loginId = '"+loginId+"'").list();
			if(null!=list && list.size()>0){
				return list.get(0);
			}
		}
		
		return null;
	}

	@Override
	public String getNameByLoginId(Integer loginId) {
		// TODO Auto-generated method stub
		if(null != loginId){
			@SuppressWarnings("unchecked")
			List<Category> list = sessionFactory.getCurrentSession().
				createQuery("from Category where loginId = '"+loginId+"'").list();
			if(null!=list && list.size()>0){
				return list.get(0).getName();
			}
		}
		return null;
	}
	
}
